package com.lge.clock;

import java.util.Calendar;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lge.clock.alarmclock.AlarmAlertWakeLock;
import com.lge.clock.alarmclock.PouchMode;
import com.lge.clock.timer.TimerWakeLock;
import com.lge.clock.timer.Timers;
import com.lge.clock.util.CommonUtil;
import com.lge.clock.util.CommonUtil.AlarmDBQueryCondition;
import com.lge.clock.util.CommonUtil.OPERATOR;
import com.lge.clock.util.CommonUtil.PrefreParent;
import com.lge.clock.util.MediaDBCondition;
import com.lge.clock.util.MediaInfoHolder;
import com.lge.clock.util.MediaInfoHolder.MediaLocation;
import com.lge.lgdrm.Drm;
import com.lge.sui.widget.control.SUIDrumTimePicker;
import com.lge.sui.widget.control.SUIDrumTimePicker.KeypadListener;
import com.lge.sui.widget.control.SUIDrumTimePicker.OnTimeChangedListener;
import com.lge.sui.widget.control.SUIDrumTimePicker.PickerScrollListener;

import static com.lge.clock.timer.Timers.TIMER_OFF_TAG;
import static com.lge.clock.util.CommonUtil.getMediaInfo;
import static com.lge.clock.util.CommonUtil.getDefaultRingToneInfo;

import android.view.*;
/**
 * @author LGE Cappuccino
 */
public class TimerFragment extends Fragment implements OnClickListener
{
	private static final String TAG = "TimerActivity";
	private static final String VIBRATION = "vibration";
	private static final String RINGTONE = "rintone";
	public static final String SETTIME = "settime";
	//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key START
	//added by essin@lge.com 2011-03-021
	private static final String TIMERSTARTED = "timerstarted";
	private static final String ENDTIME = "endtime";
	//added by essin@lge.com 2011-03-021
	//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key END
	private static final int REQUESTCODE_RINGTONE = 111;
	
	private BroadcastReceiver mSDCardMountEventReceiver = null;
    private static int mTOAST_TEXT_FOR_EMMC = 0;
	
	private LinearLayout mVib_topgroup;
	private LinearLayout mTone_topgroup;
	//[suhaeng.lee][1415] 2011.10.17
	private CheckedTextView mVib_checkbox;
	private SUIDrumTimePicker mTimePicker;
	
	private TextView mTone_textview;
	private Button mTimer_start_btn;
	private Button mTimer_cancel_btn;
	private Timer mTimer;
	private long mTime;
	private long mStartTime;
	
	private static ContentResolver mResolver;
	private static SharedPreferences mSharedPreferences;
	private static SharedPreferences.Editor mEditor;
	private static Context mContext;
	
	private int mSave_setTime;
	
	private boolean isTimerStarted = false;
	private IntentFilter mIntentFilter;
	//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key START
	//added by essin@lge.com 2010/11/05
	//private AlarmManager am;
	//private PendingIntent sender;
	//private Intent intent;
	//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key END
	private Intent ringtonePickerIntent = null;
	
	private View mDrumHourFrameLayout;
	private View mDrumMinFrameLayout;
	private View mDrumSecFrameLayout;
	//TD#29470 fixed by mo2sangbong.lee@lge.com 2011.07.22 Start	
	private long mBeforClickedTime = 0;
	private long mAfterClickedTime = 0;
	//TD#29470 fixed by mo2sangbong.lee@lge.com 2011.07.22 End	
	// [mo2sangbong.lee@lge.com][30377] 2011.08.12. timer thread duplicate issue fix START
	private boolean bTimerAlreadStarted = false;
	// [mo2sangbong.lee@lge.com][30377] 2011.08.12. timer thread duplicate issue fix END
	
	/* [START] 2012.03.09 suein1209.kim */
	/**
	 * 2012.03.09 suein1209.kim
	 */
	private AlertDialog.Builder alarmToneDialog;
	
	/**
	 * Alarm tone request code numb3r
	 */
	private final int mAlarmToneRqCode = 107;
	
	/**
	 * Alarm tone request code numb3r
	 */
	private final int mMusicRqCode = 108;
	
	/* [END] 2012.03.09 suein1209.kim */
	
	private int iEditHour = 0;
	private int iEditMin = 0;
	private int iEditSec = 0;
	
	private int iCurHour = 0;
	private int iCurMin = 0;
	private int iCurSec = 0;
	
	private boolean mPausedState = false;
	private boolean mIsScroll = false;

	private BroadcastReceiver mBroadCastReceiver = new BroadcastReceiver()//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key
	{
		public void onReceive(Context context, Intent intent) 
		{
			if(Timers.TIMER_KILLED.equals(intent.getAction()))
			{
				updatemTimePicker(loadSetTimePreferences());
				//mStartMenu.setVisible(true);
            	//mStopMenu.setVisible(false);
				mTimer_start_btn.setVisibility(View.VISIBLE);
				mTimer_cancel_btn.setVisibility(View.GONE);
				//[hyunjung78.park][18942] 2011.08.08 Fixed reset timer issue pressing back key
				//added by essin@lge.com 2011-03-21
				saveIsTimerStartedPreferences(false);
				saveEndTimePreferences(0L);
				//added by essin@lge.com 2011-03-21
				//[hyunjung78.park][18942] 2011.08.08 Fixed reset timer issue pressing back key
				setTimerStartFlag(false);
				
			}	
			//[mo2sangbong.lee][1647] 2011.11.02 START
			if("android.intent.action.TIME_SET".equals(intent.getAction()))
			{
				stopTimer();
				boolean isTimerStarted1 = loadIsTimerStartedPreferences();
				Log.e(TAG,"onReceive loadIsTimerStartedPreferences : " + isTimerStarted1);
				if(isTimerStarted1)
				{
					Long time = loadEndTimePreferences();
					updatemTimePicker((time - (SystemClock.elapsedRealtime()))/1000);
					startTimer(time);
					
					setTimerStartFlag(true);
					
					//mStartMenu.setVisible(false);
	            	//mStopMenu.setVisible(true);
					mTimer_start_btn.setVisibility(View.GONE);
					mTimer_cancel_btn.setVisibility(View.VISIBLE);
				}				
			}
			//[mo2sangbong.lee][1647] 2011.11.02 END
		}
	};

	/**
	 * Method onCreate.
	 * @param savedInstanceState Bundle
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		Window w = this.getActivity().getWindow();
//		w.setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
//		         WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
		setHasOptionsMenu(true);
		
		mSharedPreferences = getActivity().getSharedPreferences("TIMER_STATE", 0);
		mEditor = mSharedPreferences.edit();
	}
	
	/**
	 * 2012.03.27 suein1209.kim
	 * check timer ing state
	 * @return
	 */
	private boolean isTimerStarting(){
		boolean ret = false;
		if(loadIsTimerStartedPreferences()){
			long endTime = loadEndTimePreferences();
			long gapTime = endTime - SystemClock.elapsedRealtime();
			ret = true;
			if(gapTime < 0){
				ret = false;
			}//End Of if
		} //End Of if
		
		return ret;
	} //End of Method isTimerStarting
	
	@Override
	public void onStart() {
		init();
		
                mTimePicker.updateTime(0,0,0);

                /*[START] 2012.03.27 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #34287*/
//		boolean isTimerStarted1 = loadIsTimerStartedPreferences();
		boolean isTimerStarted1 = isTimerStarting();
		/*[END] 2012.03.27 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #34287*/
		Log.e(TAG,"loadIsTimerStartedPreferences : " + isTimerStarted1);
		if(isTimerStarted1)
		{
			Long time = loadEndTimePreferences();
			updatemTimePicker((time - (System.currentTimeMillis()))/1000);
			startTimer(time);
			setTimerStartFlag(true);
		}
		super.onStart();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.timer_main, container, false);
	}
	
    /**
     * 2012.01.31 suein1209.kim
     * set default ring tone
     */
//	private void setDefaultRingTone() {
//		
//		MediaInfoHolder mediaInfoHolder = getDefaultRingToneInfo((Activity)mContext, AlarmDBQueryCondition.SET_ALARM);
//
//		String preferUri = "";
//		String uiTitle = "";
//		if(mediaInfoHolder.mediaURI == null){
//			/*if silent mode*/
//			preferUri = TIMER_OFF_TAG;
//			uiTitle = getResources().getString(R.string.silent_alarm_summary);
//         	
//		}else{
//			preferUri = mediaInfoHolder.mediaURI.toString();
//			uiTitle = mediaInfoHolder.mediaTitle;
//		} //End Of if
//		
//		Log.d("suine", "setDefaultRingTone URI : "+preferUri);
//		Log.d("suine", "setDefaultRingTone TITLE : "+uiTitle);
//		
//		saveTonePreferences(preferUri);
//		mTone_textview.setText(uiTitle);
//		
//	} //End Of Method setDefaultRingTone
	
	
	/**
	 * suein1209.kim
	 * Check Silent mode
	 * @return
	 */
	private boolean isSilentMode(String uri){
		if (uri == null || "".equals(uri.trim()) || TIMER_OFF_TAG.equalsIgnoreCase(uri.trim()) ) {
			return true;
		}else{
			return false;
		} //End Of if
	} //End Of Method isSilentMode
	
	/**
	 * Method onResume.
	 */
	@Override
	public void onResume() 
	{
		super.onResume();
		
		Log.d(TAG, "[onResume]");
		bEditTimePicker = false;
		
		//[mo2sangbong.lee][1383] 2011.11.07 START
		/*[START] 2012.03.27 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #34287*/
//		boolean isTimerStarted1 = loadIsTimerStartedPreferences();
		boolean isTimerStarted1 = isTimerStarting();
		/*[END] 2012.03.27 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #34287*/
		Log.e(TAG,"loadIsTimerStartedPreferences : " + isTimerStarted1);
		if(isTimerStarted1)
		{
			Long time = loadEndTimePreferences();
			//[mo2sangbong.lee][1647] 2011.11.02 START
			updatemTimePicker((time - (SystemClock.elapsedRealtime()))/1000);
			//[mo2sangbong.lee][1647] 2011.11.02 END
			startTimer(time);
			setTimerStartFlag(true);
			
			mTimer_start_btn.setVisibility(View.GONE);
			mTimer_cancel_btn.setVisibility(View.VISIBLE);
		} else {
			setTimerStartFlag(false);
			updatemTimePicker(loadSetTimePreferences());
        	mTimer_start_btn.setVisibility(View.VISIBLE);
        	mTimer_cancel_btn.setVisibility(View.GONE);				
		}
		//[mo2sangbong.lee][1383] 2011.11.07 END
		
		/*[START] 2012.02.01 suein1209.kim refectoring*/
		String uri = loadTonePreferences();
		
		CharSequence title = "N/A";
		if(isSilentMode(uri)){
			title = getText(R.string.silent_alarm_summary);
			
		}else{
			AlarmDBQueryCondition queryCtn = CommonUtil.getBuildOperator() == OPERATOR.DCM  ? AlarmDBQueryCondition.NO_CONDITION : AlarmDBQueryCondition.SET_ALARM; 
			
			MediaInfoHolder infoHolder = CommonUtil.getFinededDefaultTone(getActivity(), uri, queryCtn, PrefreParent.TIMER);
			if(infoHolder.mediaLocation == MediaLocation.NO_WHERE){
				
				/*find default ring tone*/
				MediaInfoHolder defaultHolder = getDefaultRingToneInfo((Activity)mContext, queryCtn);
				if(defaultHolder.mediaURI != null){
					title = defaultHolder.mediaTitle;
					uri = defaultHolder.mediaURI.toString();
				} //End Of if
				
			}else{
				title = infoHolder.mediaTitle;
				uri = infoHolder.mediaURI != null ? infoHolder.mediaURI.toString() : null;
				saveTonePreferences(uri);
			}//End Of if
			
		} //End Of if(isSilentMode(uri))
		mTone_textview.setText(title);
		
		mPausedState = false;
	}

	/**
	 * Method onPause.
	 */
	@Override
	public void onPause()
	{	
		super.onPause();
		Log.d(TAG, "[onPause]");
		mPausedState = true;

		if(!isTimerStarted)
		{
			Log.e(TAG, "isTimerstart true");
                        setmSave_setTime((iEditHour*3600)+(iEditMin*60)+((iEditSec)));
                        // setmSave_setTime((mTimePicker.getCurrentHour()*3600)+(mTimePicker.getCurrentMinute()*60)+((mTimePicker.getCurrentSecond())));
		}
	}
	
	/**
	 * Method onStop.
	 */
	@Override
	public void onStop() 
	{
		super.onStop();
		Log.d(TAG, "[onStop]");
		releaseTimePicker();
	}
	
	/**
	 * Method onDestroy.
	 */
	@Override
	public void onDestroy() 
	{
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.d(TAG, "[onDestroy]");
		stopTimer();
		//releaseAlarmManager();//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key
		if (mSDCardMountEventReceiver != null) {
			try{
				getActivity().unregisterReceiver(mSDCardMountEventReceiver);
			}catch(Exception e){
				e.printStackTrace();
			}
            mSDCardMountEventReceiver = null;
        }
		if(mBroadCastReceiver != null)
		{
			try{
			getActivity().unregisterReceiver(mBroadCastReceiver);
			}catch(Exception e){
				e.printStackTrace();
			}
			mBroadCastReceiver = null;
		}
	}
	/*
	MenuItem mStartMenu;
	MenuItem mStopMenu;
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		menu.clear();
		inflater.inflate(R.menu.timer_menu, menu);
		mStartMenu = menu.findItem(R.id.timer_start_menu);
		mStartMenu.setEnabled(!isTimerStarted);
		mStartMenu.setVisible(!isTimerStarted);
		mStopMenu = menu.findItem(R.id.timer_stop_menu);
		mStopMenu.setEnabled(isTimerStarted);
		mStopMenu.setVisible(isTimerStarted);
		
	}
	
	

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case R.id.timer_start_menu:
			{
				isTimerStarted = true;
				//[mo2sangbong.lee][1647] 2011.11.02 START
            	mStartTime = SystemClock.elapsedRealtime() + (((mTimePicker.getCurrentHour()*3600)+(mTimePicker.getCurrentMinute()*60)+(mTimePicker.getCurrentSecond()))*1000)+1000; //noCappuccino
            	
            	setmSave_setTime((int)((mStartTime - (SystemClock.elapsedRealtime()))/1000)-1);
				//[mo2sangbong.lee][1647] 2011.11.02 END
				
				//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key START
				Intent intent = new Intent(Timers.TIMER_ALERT_ACTION);
		    	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
				PendingIntent sender = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
				AlarmManager am = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
				//[mo2sangbong.lee][1647,1677] 2011.11.02 START
            	am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mStartTime-800, sender);
				//[mo2sangbong.lee][1647,1677] 2011.11.02 END
            	
            	mStartMenu.setVisible(false);
            	mStopMenu.setVisible(true);
            	mTimer_start_btn.setVisibility(View.GONE);
            	mTimer_cancel_btn.setVisibility(View.VISIBLE);
				
				//added by essin@lge.com 2011-03-21
				saveIsTimerStartedPreferences(true);
				saveEndTimePreferences(mStartTime);
				//added by essin@lge.com 2011-03-21
				
				startTimer(mStartTime);
				break;
				//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key END
			}
		case R.id.timer_stop_menu:
			{
				//updatemTimePicker(mSave_setTime);//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key
            	stopTimer();
            	isTimerStarted = false;
    
            	mStartMenu.setVisible(true);
            	mStopMenu.setVisible(false);
            	mTimer_start_btn.setVisibility(View.VISIBLE);
            	mTimer_cancel_btn.setVisibility(View.GONE);	
            	releaseAlarmManager();
				//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key START
				//added by essin@lge.com 2011-03-21
				saveIsTimerStartedPreferences(false);
				saveEndTimePreferences(0L);
				//added by essin@lge.com 2011-03-21
				updatemTimePicker(loadSetTimePreferences());
				//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key END
			}
			break;
		}
		getActivity().invalidateOptionsMenu();
		return super.onOptionsItemSelected(item);
	}*/
	/**
	 * Method init.
	 */
	private void init()
	{		
		mContext = getActivity();
		mResolver = mContext.getContentResolver(); 
		bEditTimePicker = false;
		
		mSharedPreferences = this.getActivity().getSharedPreferences("TIMER_STATE", 0);
		mEditor = mSharedPreferences.edit();
		/*
		//[hyunjung78.park]2011.08.17 Fixed no timer alert after pressing back key
		//added by essin@lge.com 2010/11/05
		Intent intent = new Intent(Timers.TIMER_ALERT_ACTION);
    	       intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		PendingIntent sender = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        */
		mIntentFilter = new IntentFilter();
		mIntentFilter.addAction(Timers.TIMER_KILLED);
		//[mo2sangbong.lee][1647] 2011.11.02 START
		mIntentFilter.addAction("android.intent.action.TIME_SET");
		//[mo2sangbong.lee][1647] 2011.11.02 END
		getActivity().registerReceiver(mBroadCastReceiver, mIntentFilter);
		
		mVib_topgroup = (LinearLayout)getView().findViewById(R.id.timer_vib_topgroup);
		mVib_topgroup.setOnClickListener(this);
		
		mVib_checkbox = (CheckedTextView)getView().findViewById(R.id.timer_vibCheckbox);

		mTone_topgroup = (LinearLayout)getView().findViewById(R.id.timer_tone_topgroup);
		mTone_topgroup.setOnClickListener(this);
		
		mTone_textview = (TextView)getView().findViewById(R.id.timer_tone_sub); //seungchul.kang@lge.com Tone selection change color
		
		mTimePicker = (SUIDrumTimePicker)getView().findViewById(R.id.timepicker);
		mTimePicker.setTimeFormat(SUIDrumTimePicker.TIMEFORMAT_24_HHMMSS);
		
		mDrumHourFrameLayout = (View)mTimePicker.getHourPicker();
		mDrumMinFrameLayout  = (View)mTimePicker.getMinutePicker();
		mDrumSecFrameLayout  = (View)mTimePicker.getSecondPicker();		

//		updatemTimePicker(loadSetTimePreferences());
		
		mTimer_start_btn = (Button)getView().findViewById(R.id.timer_start_btn);
		mTimer_start_btn.setOnClickListener(this);
		mTimer_cancel_btn = (Button)getView().findViewById(R.id.timer_cancel_btn);
		mTimer_cancel_btn.setOnClickListener(this);

		mTimePicker.setOnTimeChangedListener(new OnTimeChangedListener()
		{	
			public void onTimeChanged(SUIDrumTimePicker view, int hour, int minute)  
			{
				// TODO Auto-generated method stub
				iCurHour = hour;
				iCurMin = minute;
				iCurSec = view.getCurrentSecond();
				setTimerStartBtnDisable((iCurHour + iCurMin + iCurSec) == 0);
				if(!mPausedState)
					mTimePicker.requestFocus();
			}
		});
		
		mTimePicker.setKeypadListener(new KeypadListener(){

			@Override
			public void receivedValue(String hour, String minute, String second) {
				// TODO Auto-generated method stub
				
				iEditHour = getInt(hour);
				iEditMin = getInt(minute);
				iEditSec = getInt(second);

				setTimerStartBtnDisable((iEditHour + iEditMin + iEditSec) == 0);
				bEditTimePicker = true;
			}		
			
			
		});

		mTimePicker.setPickerScrollListener(new PickerScrollListener(){

			@Override
			public void isScroll(boolean scroll) {
				// TODO Auto-generated method stub
				
				Log.d("suein", " scroll === "+scroll);
				Log.d("suein", " isTimerStarted === "+isTimerStarted);
				
	           	if(isTimerStarted)
            		return;
	           	
	           	boolean bDisable = scroll;	           
	           	mIsScroll = scroll;		
	           	
	           	if(!bDisable)
	           		bDisable = (iCurHour + iCurMin + iCurSec) == 0;
	           	Log.d("suein", " bDisable === "+bDisable);
	           	
	           	setTimerStartBtnDisable(bDisable);       
	           	
	          	
						
			}
			
		});
		
		mIsScroll = false;
		//getRingTone();
		mVib_checkbox.setChecked(loadVibPreferences());
	}
	
	private boolean bEditTimePicker = false;
	private void updateEditTimePicker(){
		if(bEditTimePicker){			
			mTimePicker.updateTime(iEditHour, iEditMin, iEditSec); 
		}
		bEditTimePicker = false;
	}
	
	private int getInt(String value){
		// WBT -- TD2170347571
		if (value == null || value.isEmpty())
			return 0;
		
		int ret = Integer.parseInt(value);
		return ret;
	}
	
	private void setTimerStartBtnDisable(boolean bDisable){
		
		if(bDisable)
		{
			if(mTimer_start_btn.isEnabled()) {
				mTimer_start_btn.setEnabled(false);
					//mTimer_start_btn.setTextColor(getActivity().getResources().getColor(R.color.start_button_disable));
				mTimer_start_btn.setAlpha(0.4f);
			}
			
		}
		else
		{
			if(!mTimer_start_btn.isEnabled()){
				if( mIsScroll )
					return;
				mTimer_start_btn.setEnabled(true);
					//mTimer_start_btn.setTextColor(getActivity().getResources().getColor(R.color.start_button));
				mTimer_start_btn.setAlpha(1.0f);
			}
		}
	}

	
    /**
     * Field toastForEmmcThread.
     */
    Runnable toastForEmmcThread = new Runnable() {
        public void run() {
            if (mTOAST_TEXT_FOR_EMMC == 1) {
                Toast.makeText(mContext, R.string.media_scanner_EJECTED, Toast.LENGTH_SHORT).show();
            }else if (mTOAST_TEXT_FOR_EMMC == 2) {
                Toast.makeText(mContext,  R.string.media_scanner_running, Toast.LENGTH_SHORT).show();
            }
        };
    };
    
//	private void legalToneSetting() {
//		Log.d(TAG, "===legalToneSetting====");
//	    	
//	    Uri alert = RingtoneManager.getActualDefaultRingtoneUri(getActivity(), RingtoneManager.TYPE_ALARM);
// 	    if (alert == null) {
// 	    	mTone_textview.setText(  this.getText(R.string.silent_alarm_summary).toString() );
//         	saveTonePreferences("Off");
// 	    } else { 
// 	    	int i = 1;
// 	    	boolean tag = false;
// 	    	String defaulttone = "", title= "";
// 	    	
// 	    	Cursor cur = null;
// 	    	try {
//				cur = mResolver.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, INTERNAL_COLUMNS,
//									               			"is_alarm = 1",  null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER); 	            
//				if (cur != null && cur.moveToFirst()) {//[hyunjung78.park] 2011.08.09 cursor null check
//					do {
//				        Uri uri1 = ContentUris.withAppendedId(Uri.parse(cur.getString(2)), cur.getLong(0));
//				        if (uri1.toString().equalsIgnoreCase(alert.toString())) {
//				        	mTone_textview.setText( cur.getString(1) );
//	                        
//	                        /*[START]2012.01.26 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #125508*/
//	                        saveTonePreferences(uri1.toString());
//	                        
////	                        Object status = Environment.getExternalStorageState();
////							if (status.equals(Environment.MEDIA_MOUNTED) ||
////							        status.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
////								saveTonePreferences(uri1.toString());
////							}
//	                        /*[END]2012.01.26 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #125508*/
//				         	tag = true;
//				            break;
//				        }
//				         
//				        if (i == 4) {
//				        	defaulttone = uri1.toString();
//				        	title = cur.getString(1);
//				        }
//				        i++;
//					} while (cur.moveToNext());
//				}
//			} catch (Exception e) {
//				e.printStackTrace();
//			} finally {
//				if ( cur != null )
//					cur.close();
//			}
//	     	        
//	     	if (tag == false) { 
//	     		mTone_textview.setText( title );
//	           	saveTonePreferences(defaulttone);      
//	     	}
// 	    }
//	}
	
	private void startTimer(long startTime)
	{
    	//TD#30377 fixed by mo2sangbong.lee@lge.com 2011.07.27 Start
    	// [mo2sangbong.lee@lge.com][30377] 2011.08.12. timer thread duplicate issue fix START	
    	if (bTimerAlreadStarted == true) {
    		Log.e(TAG, "Timer thread is already started");
    		return;
    	}
    	bTimerAlreadStarted = true;
    	// [mo2sangbong.lee@lge.com][30377] 2011.08.12. timer thread duplicate issue fix END  	
    	
		Log.d(TAG, "[startTimer] : start the timer");
		mStartTime = startTime;
		mTimer = new Timer();
		
		mTimer.scheduleAtFixedRate(new TimerTask()
		{
			@Override
			public void run() 
			{
				//[mo2sangbong.lee][1647] 2011.11.02 START
				mTime = ((mStartTime - (SystemClock.elapsedRealtime()))/1000);
				//[mo2sangbong.lee][1647] 2011.11.02 END
				//timer playing
				if(0 < (int)mTime)
				{	
					if ( bTimerAlreadStarted == true) {
						updatemTimePicker(mTime);
					}
				}
				//timer stop
				else
				{
					if ( bTimerAlreadStarted == true) {
						updatemTimePicker(mTime);				
					}
			    	stopTimer();
				}
			}
		}, 0, 1000);
	}
	
	private void stopTimer()
	{	
		// [mo2sangbong.lee@lge.com][30377] 2011.08.12. timer thread duplicate issue fix START
		bTimerAlreadStarted = false;
		// [mo2sangbong.lee@lge.com][30377] 2011.08.12. timer thread duplicate issue fix END		
		if(mTimer != null)
		{
			mTimer.cancel();
		}
		//getActivity().runOnUiThread(new Thread(){public void run(){getActivity().invalidateOptionsMenu();}});
	}

	/**
	 * Method releaseLocks.
	 */
	public static void releaseLocks() {
        //AlarmAlertWakeLock.release();
		TimerWakeLock.release();
    }

	private void updatemTimePicker(final long value)
	{
		Runnable runnable = new Runnable()
		{
			public void run() 
			{				
				long time = value;
				mTimePicker.updateTime((int)(time)/3600,(int)(time/60)%60, (int)(time)%60); //noCappuccino
			}
		};
		
		getActivity().runOnUiThread(runnable);	
	}
	//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key START
	//added by essin@lge.com 2011-03-21
	public static void saveIsTimerStartedPreferences(boolean isTimer)
	{
		mEditor.putBoolean(TIMERSTARTED, isTimer);
		mEditor.commit();
	}
	
	public static boolean loadIsTimerStartedPreferences()
	{
		return mSharedPreferences.getBoolean(TIMERSTARTED, false);
	}
	
	public static void saveEndTimePreferences(Long endtime)
	{
		mEditor.putLong(ENDTIME, endtime);
		mEditor.commit();
	}
	
	public static Long loadEndTimePreferences()
	{
		return mSharedPreferences.getLong(ENDTIME, 0);
	}
	//added by essin@lge.com 2011-03-21
	//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key END
	private void saveVibPreferences(boolean isVib)
	{	
		mEditor.putBoolean(VIBRATION, isVib);
		mEditor.commit();
	}
	
	/**
	 * Method saveTonePreferences.
	 * @param tone String
	 */
	public static void saveTonePreferences(String tone)
	{
		mEditor.putString(RINGTONE, tone);
		mEditor.commit();
	}
	
	private void saveSetTimePreferences(int settime)
	{
		mEditor.putInt(SETTIME, settime);
		mEditor.commit();
	}
	
	/**
	 * Method loadVibPreferences.
	 * @return boolean
	 */
	public static boolean loadVibPreferences()
	{
		return mSharedPreferences.getBoolean(VIBRATION, true);
	}
	
	/**
	 * Method loadTonePreferences.
	 * @return String
	 */
	public static String loadTonePreferences()
	{
		MediaInfoHolder mdfHolder= CommonUtil.getDefaultRingToneInfo(mContext, AlarmDBQueryCondition.SET_ALARM);
//		MediaInfoHolder mdfHolder= CommonUtil.getOperatorDefaultMediaInfo(mResolver);
		
		String uri = mdfHolder.mediaURI == null ? null : mdfHolder.mediaURI.toString();
		return mSharedPreferences.getString(RINGTONE, uri == null ? "Off" : uri.toString());
	}
	
	private int loadSetTimePreferences()
	{
		return mSharedPreferences.getInt(SETTIME, 0);
	}
	
//	private static final String[] INTERNAL_COLUMNS = new String[] {
//		android.provider.BaseColumns._ID, 
//		android.provider.MediaStore.MediaColumns.TITLE,
//		"\"" + MediaStore.Audio.Media.INTERNAL_CONTENT_URI + "\"",
//		android.provider.MediaStore.Audio.AudioColumns.TITLE_KEY
//	};
//	
//	private static final String[] EXTERNAL_COLUMNS = new String[] {
//	    android.provider.BaseColumns._ID,
//		android.provider.MediaStore.MediaColumns.TITLE,
//		"\"" + MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "\"",
//		android.provider.MediaStore.Audio.AudioColumns.TITLE_KEY
//	};

//	/**
//	 * Method defaultRingtone.
//	 * @return String
//	 */
//	public static String defaultRingtone() {
//		String defaultTone = "";
//	    Uri alert = RingtoneManager.getActualDefaultRingtoneUri(mContext, RingtoneManager.TYPE_ALARM);
//	    
//		if (alert == null) {
//			defaultTone	= "Off";
//			return defaultTone;
//		}
//		
//	    ContentResolver resolver = mContext.getContentResolver();
//	    
//	    Cursor cur = null;
//        try {
//			cur = resolver.query(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, INTERNAL_COLUMNS,
//							               "is_alarm = 1",  null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER); 
//			
//			String temp = defaultRingtoneTitle();
//			Log.d(TAG, "=>" + temp + "<=" );
//			
//			if (cur != null && cur.moveToFirst()) {//[hyunjung78.park] 2011.08.09 cursor null check
//				do {  // Get the field values
//					Uri uri1 = ContentUris.withAppendedId(Uri.parse(cur.getString(2)), cur.getLong(0));
//			        int aa = (cur.getString(1)).indexOf( temp );
//			        if ( aa >=0 ) {
//			        	Log.d(TAG, temp + " / Title=" +  cur.getString(1)  +   "<==  URI ==>" + uri1.toString() ) ;
//			        	defaultTone	=	uri1.toString() ;	
//			        	break;
//			        }
//			          
//				} while (cur.moveToNext());
//			}         
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			if ( cur != null )
//				cur.close();
//		}
//	 	
//	 	if ("".equals(defaultTone.trim())) {
//	 		defaultTone	= "Off";  
//	 	}
//	 	      
//	 	Log.d(TAG, "====defaultTone======>" +  defaultTone );
//	 	return defaultTone ;
//	}
//      
//    private static String defaultRingtoneTitle() {
//    	Uri alert = RingtoneManager.getActualDefaultRingtoneUri(mContext, RingtoneManager.TYPE_ALARM);
//	    
//    	if (alert != null) {
//    		final Ringtone r = RingtoneManager.getRingtone(mContext, alert);
//    		if (r != null) {
//    			Log.d(TAG, "=default===> " + r.getTitle(mContext)  ); //+ "  /  " + r.get );
//    			return r.getTitle(mContext);  
//    		}
//    	}
//    	
//    	return "" ;
//    }
	
	/**
	 * Method onActivityResult.
	 * @param requestCode int
	 * @param resultCode int
	 * @param data Intent
	 */
    @Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		if(REQUESTCODE_RINGTONE == requestCode)
		{
			// MonkeyTest
			try {
				if (mTone_topgroup == null)
					mTone_topgroup = (LinearLayout) getView().findViewById(
							R.id.timer_tone_topgroup);
				if (mTone_topgroup != null) {
					mTone_topgroup.setFocusable(true);
					mTone_topgroup.setClickable(true);
				}
			} catch (Exception e) {
			}
			
			if (data != null && getActivity().RESULT_OK == resultCode){
				String toneText = "N/A";
				String toneUri = "N/A";
				
					Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
					if (uri == null) {     	
						toneText = this.getText(R.string.silent_alarm_summary).toString();
						toneUri = "Off";
					} else if (uri != null){
						
						MediaInfoHolder mediaInfo = CommonUtil.getMediaInfo(mResolver, uri, AlarmDBQueryCondition.NO_CONDITION);
	//					Log.d("suein", "===123==>>>>>>>" + uri.toString()  +  data.getStringExtra("") );
	//					toneText = uri.toString();
	//					
	//					Cursor cur = null;
	//					try {
	//						cur = mResolver.query(uri, new String[] { "title" }, null, null, null);
	//						if (cur != null && cur.moveToFirst()) {//[hyunjung78.park] 2011.08.09 cursor null check
	//							do {
	//								toneText = cur.getString(0);
	//							} 
	//							while (cur.moveToNext());
	//						}
	//					} catch( Exception e ) {
	//						e.printStackTrace();
	//					} finally {
	//						if ( cur != null )
	//							cur.close();
	//					}
						
						CommonUtil.setBackupToneInfoValue(mContext, mediaInfo, PrefreParent.TIMER);
						
						toneText = mediaInfo.mediaTitle;
						toneUri = mediaInfo.mediaURI != null ? mediaInfo.mediaURI.toString() : null;
					}
				
				saveTonePreferences(toneUri);
				mTone_textview.setText(toneText);
			} //End Of if (data != null && getActivity().RESULT_OK == resultCode){
			
		}else if(requestCode == mMusicRqCode){
        	/*2012.03.09 suein1209.kim*/
        	
        	if (resultCode==Activity.RESULT_OK) {
        		Uri uri = data.getData();
        		
        		String []proj = {MediaStore.MediaColumns.TITLE,MediaStore.MediaColumns.DATA};        				
        		//Cursor cursor = ((Activity)mContext).managedQuery (uri, proj, null, null, null);
        		
        		CursorLoader cursorLoader = new CursorLoader(
    					getActivity(), 
    					uri, 
    					proj, 
    			        null, 
    			        null, 
    			        null);
        		
        		/*[START] 2012.03.28 suein1209.kim INTERNAL_TEST.WBT_12 - Defect #329172 */
        		boolean reFlag = false;
        		if(cursorLoader != null){
        			Cursor cursor = cursorLoader.loadInBackground();
        			if(cursor != null){
        				int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.TITLE); 
        				cursor.moveToFirst(); 
        				String title = cursor.getString(index);
        				index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA); 
        				saveTonePreferences(uri.toString());
        				mTone_textview.setText(title);
        				
        				/*set setting flag*/
        				reFlag = true;
        				
        				cursor.close();
        				
        			} //End Of if
        		} //End Of if
        		if(reFlag == false){
        			/*There is no null point exception*/
        			mTone_textview.setText(this.getText(R.string.silent_alarm_summary).toString());
        		} //End of if
        		/*[END] 2012.03.28 suein1209.kim INTERNAL_TEST.WBT_12 - Defect #329172  */
        		
        		

        	}
        } //End Of if
		
    	ringtonePickerIntent = null;
	}
    
	private long getmSave_setTime() 
	{
		return mSave_setTime;
	}

	private void setmSave_setTime(int mSaveSetTime) 
	{
		
//		if(mSave_setTime != mSaveSetTime)
//		{
			mSave_setTime = mSaveSetTime;
			saveSetTimePreferences(mSaveSetTime);
//		}
	}

	//added by essin@lge.com 2010/11/06
	private void releaseAlarmManager()
	{
		//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key START
		AlarmManager am = (AlarmManager)getActivity().getSystemService(getActivity().ALARM_SERVICE);
		Intent intent = new Intent(Timers.TIMER_ALERT_ACTION);
		PendingIntent sender = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
		//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key END
		if(am != null)
		{
			am.cancel(sender);
			am = null;
		}
	}
	
    /**
     * Method onClick.
     * @param v View
     * @see android.view.View$OnClickListener#onClick(View)
     */
   
    public void onClick(View v) 
    {
        switch(v.getId())
        {
            case R.id.timer_start_btn :
            {	
            	if(isTimerStarted)
            		return;
 
            	if(mIsScroll)
            		return;
            	
            	doStartTimer();
				break;
				//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key END
			}
			
            case R.id.timer_cancel_btn :
            {
            	//updatemTimePicker(mSave_setTime);//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key
            	stopTimer();
            	setTimerStartFlag(false);
            	
            	//mStartMenu.setVisible(true);
            	//mStopMenu.setVisible(false);
            	mTimer_start_btn.setVisibility(View.VISIBLE);
            	mTimer_cancel_btn.setVisibility(View.GONE);	
            	releaseAlarmManager();
				//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key START
				//added by essin@lge.com 2011-03-21
				saveIsTimerStartedPreferences(false);
				saveEndTimePreferences(0L);
				//added by essin@lge.com 2011-03-21
				updatemTimePicker(loadSetTimePreferences());
				//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key END
				mIsScroll = false;
			}
				break;
			
            case R.id.timer_vib_topgroup :
                if( mVib_checkbox.isChecked() ) {
                    mVib_checkbox.setChecked(false);
                    saveVibPreferences(false);
                }
                else {
                    mVib_checkbox.setChecked(true);
                    saveVibPreferences(true);
                }
                break;
			    
            case R.id.timer_tone_topgroup :
        		//TD#29470 fixed by mo2sangbong.lee@lge.com 2011.07.22 Start
        		long mTimeGap = 0;
        		
        		mAfterClickedTime = SystemClock.elapsedRealtime();
        		mTimeGap = mAfterClickedTime - mBeforClickedTime;
        		if (mTimeGap < ViewConfiguration.getDoubleTapTimeout() * 3) {
        			return;
        		} else {
        			mBeforClickedTime = SystemClock.elapsedRealtime();
        		}
        		//TD#29470 fixed by mo2sangbong.lee@lge.com 2011.07.22 End   
        		
        		/*[START] 2012.03.09 suein1209.kim */
        		if(CommonUtil.getBuildOperator() == OPERATOR.DCM ){
            		showAlarmToneSelectDialog();
            	}else{
            		startRingToneDialog();
            	} //End Of if
        		/*[END] 2012.03.09 suein1209.kim */
                
        		mTimePicker.clearFocus();
        		mIsScroll = false;
                break;
			
            default :
            	break;
		}	
	}
	
    private void doStartTimer(){    	
    	updateEditTimePicker();
    	//[haesun.jung][2967] 2012.01.06 START
    	hideKeyboard();
    	//[haesun.jung][2967] 2012.01.06 END
    	
    	setTimerStartFlag(true);
    	
    	mTimePicker.clearFocus();
    	            	
		//[mo2sangbong.lee][1647] 2011.11.02 START
    	long mElapsedRealTime = SystemClock.elapsedRealtime();
    	mStartTime =  mElapsedRealTime + (((mTimePicker.getCurrentHour()*3600)+(mTimePicker.getCurrentMinute()*60)+(mTimePicker.getCurrentSecond()))*1000)+1000; //noCappuccino
    	setmSave_setTime((int)((mStartTime - mElapsedRealTime)/1000)-1);
		//[mo2sangbong.lee][1647] 2011.11.02 END
		
		//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key START
		Intent intent = new Intent(Timers.TIMER_ALERT_ACTION);
    	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		PendingIntent sender = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
		AlarmManager am = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
		//[mo2sangbong.lee][1647,1677] 2011.11.02 START
		// [haesun.jung][WBT 325979] 2012.03.09
		if(am != null){
			am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, mStartTime-800, sender);
		}
		//[mo2sangbong.lee][1647,1677] 2011.11.02 END
    	
    	//mStartMenu.setVisible(false);
    	//mStopMenu.setVisible(true);
    	mTimer_start_btn.setVisibility(View.GONE);
    	mTimer_cancel_btn.setVisibility(View.VISIBLE);
		
		//added by essin@lge.com 2011-03-21
		saveIsTimerStartedPreferences(true);
		saveEndTimePreferences(mStartTime);
		//added by essin@lge.com 2011-03-21		

		startTimer(mStartTime);				
    }
    
    /**
     * 2012.03.09 suein1209.kim
     */
    private void showAlarmToneSelectDialog(){
    	/*Exception*/
		if (this.alarmToneDialog != null) return ;
		
		final int IDX_ALARM_TONE = 0;
		final int IDX_MUSIC = 1;
		
    	CharSequence[] alarmTypeList = new CharSequence[2];
    	alarmTypeList[IDX_ALARM_TONE] = this.getResources().getString(R.string.alarm_setting_tone); 
    	alarmTypeList[IDX_MUSIC] = this.getResources().getString(R.string.sp_TXT_Music_SHORT); 
    	
		alarmToneDialog = new AlertDialog.Builder(mContext);  	
		alarmToneDialog
		.setTitle(R.string.timer_alerttone)
		.setOnCancelListener(new OnCancelListener() { 
			public void onCancel(DialogInterface dialog) { 
					if(alarmToneDialog != null) {
						// [minjoong.park][1443] 2011.10.17. START
						CommonUtil.STOP_DIALOG_REDUNDANCY = true;
						// [minjoong.park][1443] 2011.10.17. END
						alarmToneDialog = null;
					}
			}
		}).setNeutralButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				
			    // [minjoong.park][1443] 2011.10.17. START
				CommonUtil.STOP_DIALOG_REDUNDANCY = true;
				// [minjoong.park][1443] 2011.10.17. END
				
				alarmToneDialog = null;
			}
		}).setItems(alarmTypeList, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int typeInd3x) {
				
				switch (typeInd3x) {
				case IDX_ALARM_TONE :
					startRingToneDialog();
					break;
					
				case IDX_MUSIC :
					startMusicActivity();
					break;
					
				default:
					/*DO Nothing*/
					break;
				} //End Of swithc
				
				/*dialog redundancy*/
				CommonUtil.STOP_DIALOG_REDUNDANCY = true;
				alarmToneDialog = null;
			} //End Of switch
		}).show();
		
    } //End Of Method getAlarmToneDialogInstance
    
    /**
     * 2012.03.09 suein1209.kim
     */
    private void startRingToneDialog(){
    	if(ringtonePickerIntent != null) return;
    	
    	/*[START]2012.01.26 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #125508*/
        
        String tone = loadTonePreferences();
        
        /*[END]2012.01.26 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #125508*/
        
        Uri findTone = Uri.parse(tone);
        
        if ( tone == null || tone.equalsIgnoreCase("Off") || "".equals(tone.trim())) {
            findTone = null;
        }
        
        ringtonePickerIntent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
        ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, findTone);
        ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, false);
        ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true);
        ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALARM);
        if(CommonUtil.getBuildOperator() == OPERATOR.DCM ){        
        	ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, TimerFragment.this.getResources().getString(R.string.alarm_setting_tone));
        } else {
        	ringtonePickerIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, TimerFragment.this.getResources().getString(R.string.timer_alerttone));
        }
        startActivityForResult(ringtonePickerIntent, REQUESTCODE_RINGTONE);
      
    } //End Of Method startRingToneDialog
    	
    /**
     * 2012.03.09 suein1209.kim
     */
    private void startMusicActivity(){
    	
    	final Intent intent = new Intent();    	
		intent.setClassName("com.lge.music", "com.lge.music.MusicPicker");
        intent.setAction(Intent.ACTION_GET_CONTENT); 
        intent.putExtra(Drm.EXTRA_CONTENT_ACTION , Drm.CONTENT_ACT_FORWARD);
        startActivityForResult(intent, mMusicRqCode);
        
    } //End Of Method 
    
	/**
	 * Method onKeyDown.
	 * @param keyCode int
	 * @param event KeyEvent
	 * @return boolean
	 * @see android.view.KeyEvent$Callback#onKeyDown(int, KeyEvent)
	 */
	 //[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key START
	/*
	@SuppressWarnings("static-access")
	@Override
	
	public boolean onKeyDown(int keyCode, KeyEvent event) 
	{
		// TODO Auto-generated method stub
		
		if( android.view.KeyEvent.KEYCODE_BACK == keyCode )
		{
			if(isTimerStarted)
			{
				updatemTimePicker(mSave_setTime);
				stopTimer();
				//TD#30377 fixed by mo2sangbong.lee@lge.com 2011.07.27 Start
				//isTimerStarted = false;
				//TD#30377 fixed by mo2sangbong.lee@lge.com 2011.07.27 End
//				mDrumJob = DEFALULT_NOT_drum;
				mTimer_start_btn.setVisibility(View.VISIBLE);
				mTimer_cancel_btn.setVisibility(View.GONE);
				releaseAlarmManager();
				return true;
			}
			else
			{
				return false;
			}
		}
		return super.onKeyDown(keyCode, event);
	}
       */
	//[hyunjung78.park][18942] 2011.08.04 Fixed reset timer issue pressing back key END
 // Remove dispatchTouchEvent if WVGA or HD
	private static final int DEFALULT_NOT_DRUM = 0;
	private static final int JOB_HOUR = 1;
	private static final int JOB_MIN = 2;
	private static final int JOB_SEC = 3;
	private int mDrumJob = DEFALULT_NOT_DRUM;
	
	private int[] hVL = new int[2];
	private int[] mVL = new int[2];
	private int[] sVL = new int[2];
	
	private int[] timerHVL = new int[2];
	
	/**
	 * Method dispatchTouchEvent.
	 * @param ev MotionEvent
	 * @return boolean
	 * @see android.view.Window$Callback#dispatchTouchEvent(MotionEvent)
	 */
	public boolean dispatchTouchEvent(MotionEvent ev) {
		
		if( isTimerStarted == true && filterTouchEvent(timerHVL, ev.getY(), ev.getX(), ev) == true ) {
			return true;
		} else {
			//Log.d(TAG, "dispatchTouchEvent Action=" + ev.getAction() + " X=" + ev.getX() + " Y=" + ev.getRawY());
		
			if( DEFALULT_NOT_DRUM != mDrumJob ) {
				//Log.d(TAG, "dispatchTouchEvent : mDrumJob != 0 ----->" + mDrumJob);
				drumTouch(ev, mDrumJob);
				
				if ( MotionEvent.ACTION_UP == ev.getAction() ) {
					mDrumJob = DEFALULT_NOT_DRUM;
				}
				return true;
			} else if ( filterTouchEvent(hVL, mVL, sVL, ev.getRawY(), ev.getX(), ev) ) {
				//Log.d(TAG, "dispatchTouchEvent : time zone" + mDrumJob);
				return true;
			} else {
				//Log.d(TAG, "dispatchTouchEvent : else" + mDrumJob);
				return super.getActivity().dispatchTouchEvent(ev);
			}
		}
	}
	
	// Timer Touch
	private boolean filterTouchEvent(int[] nHVL, float eY , float eX, MotionEvent ev) {
		
		mTimePicker.getLocationInWindow(nHVL);
		
		try {
			if ( (nHVL[0] < eX) && (eX < mTimePicker.getMeasuredWidth() + nHVL[0]) && 
				 (nHVL[1]-140 < eY) && (eY < mTimePicker.getMeasuredHeight() + 10 + nHVL[1] - 100) ) {
				return true;
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return false;
	}
	
	private int mHourDrumWidth = 0, mHourDrumHeight = 0, mMinDrumWidth = 0, mMinDrumHeight = 0, mSecDrumWidth = 0, mSecDrumHeight = 0; 
	
	// Drum Touch
	private boolean filterTouchEvent(int[] hVL , int[] mVL , int[] sVL, float eY , float eX, MotionEvent ev) {	
		mDrumHourFrameLayout.getLocationOnScreen(hVL);
		mDrumMinFrameLayout.getLocationOnScreen(mVL);
		mDrumSecFrameLayout.getLocationOnScreen(sVL);
		
		mHourDrumWidth  = mDrumHourFrameLayout.getMeasuredWidth();
		mHourDrumHeight = mDrumHourFrameLayout.getMeasuredHeight();
		mMinDrumWidth   = mDrumMinFrameLayout.getMeasuredWidth();
		mMinDrumHeight  = mDrumMinFrameLayout.getMeasuredHeight();
		mSecDrumWidth   = mDrumSecFrameLayout.getMeasuredWidth();
		mSecDrumHeight  = mDrumSecFrameLayout.getMeasuredHeight();
		
		//Log.e("DELETE", "filterTouchEvent Action=" + ev.getAction() + " X=" + ev.getX() + " Y=" + ev.getY());
		//Log.e("DELETE", "hVWidth : " + hVWidth + "hVHeight : " + hVHeight + "mVWidth : " + mVWidth + "mVHeight : " + mVHeight);
		//Log.e("DELETE", "hVL[0] : " + hVL[0] + "hVL[1] : " + hVL[1] + "mVL[0] : " + mVL[0] + "mVL[1] : " + mVL[1]);
		
		try {
			if ( (hVL[0]-10 < eX) && (eX < hVL[0] + mHourDrumWidth ) &&
				 (hVL[1]-10 < eY) && (eY < hVL[1] + mHourDrumHeight + 10) ) {
				if( MotionEvent.ACTION_DOWN == ev.getAction() ) {
					//Log.e("DELETE", "1" + "   " + (hVL[0]-10) + "   " + eX + "   " + (hVWidth + hVL[0]) + "   " +  (hVL[1]-10) + "   " +  eY + "   " +  (hVHeight+10 + hVL[1]) );
					mDrumJob = JOB_HOUR;
					drumTouch(ev, JOB_HOUR);
				}
				return true;
			}
			else if( (mVL[0]-10 < eX) && (eX < mVL[0] + mMinDrumWidth ) && 
					 (mVL[1]-10 < eY) && (eY < mVL[1] + mMinDrumHeight + 10) ) {
				if( MotionEvent.ACTION_DOWN == ev.getAction() ) {
					//Log.e("DELETE", "2");
					mDrumJob = JOB_MIN;
					drumTouch(ev, JOB_MIN);
				}
				return true;
			}
			else if( (sVL[0]-10 < eX) && (eX < sVL[0] + mSecDrumWidth ) && 
					 (sVL[1]-10 < eY) && (eY < sVL[1] + mSecDrumHeight + 10) ) {
				if( MotionEvent.ACTION_DOWN == ev.getAction() ) {
					//Log.e("DELETE", "3");
					mDrumJob = JOB_SEC;
					drumTouch(ev, JOB_SEC);
				}
				return true;
			}
		} catch(Exception e) {
			e.printStackTrace();
			System.out.println("null checking");
		}
		
		return false;
	}
	
	private void drumTouch(MotionEvent ev, int jobFlag) {
		switch(jobFlag) {
			case JOB_HOUR:
				ev.setLocation(ev.getX() - hVL[0], ev.getRawY() - hVL[1]);
				mTimePicker.getHourPicker().onTouchEvent(ev);
				break;
			case JOB_MIN:
				ev.setLocation(ev.getX() - mVL[0], ev.getRawY() - mVL[1]);
				mTimePicker.getMinutePicker().onTouchEvent(ev);
				break;
			case JOB_SEC:
				ev.setLocation(ev.getX() - sVL[0], ev.getRawY() - sVL[1]);
				mTimePicker.getSecondPicker().onTouchEvent(ev);
				break;
			default:
				break;
		}
	}
	
	private void hideKeyboard(){
		InputMethodManager im = (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
		
		if(im != null){
			im.hideSoftInputFromWindow(mTimePicker.getWindowToken(), 0);
		}
	}
	
	private void setTimerStartFlag(boolean bStart){
		isTimerStarted = bStart;
    	mTimePicker.setEnabled(!bStart);
	}
	
	private void releaseTimePicker(){
		if(mTimePicker != null){
			mTimePicker.setPickerScrollListener(null);
			mTimePicker.setKeypadListener(null);
			mTimePicker.setOnTimeChangedListener(null);
		}
	}
}

